package qgs.zisu.javaconcurrency.javaconcurrency.chapter11_ExitCapture;

/**
 * @Author: 蔡翔
 * @Date: 2019/10/20 11:15
 * @Version 1.0
 */

public class ExitCapture {
    public static void main(String[] args) {
        //注册一个hook（钩子）,当系统出现异常或者宕机的时候，有机会去做一些事情。
        // 就是当外部kill 这个线程的时候，这个钩子还是能做一些事情。
        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            System.out.println("The application will be exit");
            notifyAndRelease();
        }));
        int i = 0;
        while (true){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("i am working");
            i++;
            if(i>20){
                throw new RuntimeException("error");
            }
        }
    }
    private static void notifyAndRelease(){
        System.out.println("notify to the admin");
        try {
            Thread.sleep(1_000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("will release resource(socket/file/connection.)");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Release and notify down");
    }
}
